<?php
require_once(dirname(__FILE__).'/Abstract.php');
class Prescription extends AbstractDoctorController 
{
    public function indexAction()
    {
    	$this->listingAction();
    }

    public function listingAction()
    {
    	$joinFeature = array();
        
        $joinFeature[] = array(
            'type'     => 'LEFT JOIN', // LEFT JOIN, RIGHT JOIN, INNER JOIN, etc...
            'table'    => '`medic_consultation` cons', // An existing table with alias 
            'onclause' => 'cons.id_consultation = ConsultationPrescriptionORM.id_consultation', // 
            'select'   => 'cons.id_patient', // For select clause
        );
        $joinFeature[] = array(
            'type'     => 'LEFT JOIN', // LEFT JOIN, RIGHT JOIN, INNER JOIN, etc...
            'table'    => '`medic_user_entity` users', // An existing table with alias 
            'onclause' => 'users.id_user = cons.id_patient', // 
            'select'   => 'users.lastname, users.firstname', // For select clause
        );
        $joinFeature[] = array(
            'type'     => 'LEFT JOIN', // LEFT JOIN, RIGHT JOIN, INNER JOIN, etc...
            'table'    => '`medic_user_patient` patients', // An existing table with alias 
            'onclause' => 'patients.id_user = cons.id_patient', // 
            'select'   => '', // For select clause
        );
        $joinFeature[] = array(
            'type'     => 'LEFT JOIN',
            'table'    => '`medic_user_role_lang` url',
            'onclause' => 'users.id_role = url.id_role AND url.lang = \''. $this->session->userdata('lang') .'\'',
            'select'   => 'url.`name` AS role_name',
        );
 
        $d = $this->initListing('ORM/Consultation/ConsultationPrescriptionORM', 'id_prescription', 'medic_consultation_prescription', false, null, null, $joinFeature);
        
        
        $d['title'] = $this->l('List of prescriptions');
        //$d['prescriptions'] = $this->getAllPrescriptions($this->session->userdata('id_user'));
        // Read all other prescription of this doctor
        //$d['prescriptions'] = $this->ConsultationMetier->getPrescriptions($config=array('id_doctor'=>(int)$this->session->userdata('id_user')));

        $d['title_for_layout'] = $this->l('prescriptions list.');
        $d['menu'] = 'patients';
        $d['page_name'] = 'prescriptions_list';
        
        $this->load->view('Templates/Layouts/Doctor/header', $d);
        $this->load->view('Doctor/Prescription/Listing', $d);
        $this->load->view('Templates/Layouts/Doctor/footer', $d);

    }

    public function createAction()
    {
    	$d = array();
        $d['title'] = $this->l('Create a prescription');

        if ($this->input->post('btn_submit') !== false){
             // Initialized the form validation
            $config = array(
               array(
                     'field'   => 'id_consultation', 
                     'label'   => $this->l('Consultation'), 
                     'rules'   => 'trim|required|xss_clean'
                  ),
               array(
                     'field'   => 'content', 
                     'label'   => $this->l('Content'), 
                     'rules'   => 'trim|required|xss_clean'
                  ),
            );
            $this->form_validation->set_rules($config);
            if ($this->form_validation->run() == FALSE ){
                $this->session->set_flashdata('errorMessage', $this->l('An error occured. Please check filled data and try again.'));
            } else {
                // $this->load->model('ORM/Consultation/ConsultationPrescriptionORM');
                // Initialize the new record
                $record = array(
                    'content'        => $this->input->post('content'),
                    'id_consultation'=> $this->input->post('id_consultation'),                   
                    // Automatic fill                           
                    'status'        => 1,
                    'date_add'       => @date('Y-m-d H:i:s'),
                    'date_upd'       => @date('Y-m-d H:i:s'),
                );
                // Create the new prescription
                if ($this->ConsultationPrescriptionORM->save($record)) {
                    // Redirect to the sign in form
                    redirect('Doctor/Prescription/listing');
                    die();
                } else {
                    $this->session->set_flashdata('errorMessage', $this->l('An error occured while saving your prescription. Please try again.'));
                }
            }
        } 

        // Read all other consultations of this doctor
        $d['consultations'] = $this->ConsultationMetier->getConsultations($config=array('id_doctor'=>(int)$this->session->userdata('id_user')));
 

        $d['title_for_layout'] = $this->l('Creating a prescription.');
        $d['menu'] = 'prescriptions';
        $d['page_name'] = 'creating_prescription';
        
        $this->load->view('Templates/Layouts/Doctor/header', $d);
        $this->load->view('Doctor/Prescription/Create', $d);
        $this->load->view('Templates/Layouts/Doctor/footer', $d);
    }

    public function updateAction()
    {
    	$d = array();
        $d['title'] = $this->l('Update a prescription');

        if ($this->input->post('btn_submit') !== false){
             // Initialized the form validation
            $config = array(
            	array(
                     'field'   => 'id_prescription', 
                     'label'   => $this->l('Consultation'), 
                     'rules'   => 'trim|required|xss_clean'
                  ),
               	array(
                     'field'   => 'id_consultation', 
                     'label'   => $this->l('Consultation'), 
                     'rules'   => 'trim|required|xss_clean'
                  ),
               	array(
                     'field'   => 'content', 
                     'label'   => $this->l('Content'), 
                     'rules'   => 'trim|required|xss_clean'
                  ),
               	array(
                     'field'   => 'status', 
                     'label'   => $this->l('Status'), 
                     'rules'   => 'trim|required|xss_clean'
                  ),
            );
            $this->form_validation->set_rules($config);
            if ($this->form_validation->run() == FALSE ){
                $this->session->set_flashdata('errorMessage', $this->l('An error occured. Please check filled data and try again.'));
            } else {
                // $this->load->model('ORM/Consultation/ConsultationPrescriptionORM');
                // Initialize the new record
                $record = array(
                    'id_prescription'=> $this->input->post('id_prescription'),
                    'id_consultation'=> $this->input->post('id_consultation'),  
                    'content'        => $this->input->post('content'),
                    'status'         => $this->input->post('status'),                 
                    // Automatic fill 
                    'date_add'       => @date('Y-m-d H:i:s'),
                    'date_upd'       => @date('Y-m-d H:i:s'),
                );
                // Create the new prescription
                if ($this->ConsultationPrescriptionORM->save($record)) {
                    // Redirect to the sign in form
                    redirect('Doctor/Prescription/listing');
                    die();
                } else {
                    $this->session->set_flashdata('errorMessage', $this->l('An error occured while saving your prescription. Please try again.'));
                }
            }
        } 
        //debug($this->ConsultationMetier->getPrescriptions($config=array('id_prescription'=>(int)$this->input->get_post('id'))));die();
        $d['prescription'] = $this->ConsultationMetier->getPrescriptions($config=array('id_prescription'=>(int)$this->input->get_post('id')));
        // Read all other consultations of this doctor
        $d['consultations'] = $this->ConsultationMetier->getConsultations($config=array('id_doctor'=>(int)$this->session->userdata('id_user')));

        $d['title_for_layout'] = $this->l('Updating a prescription.');
        $d['menu'] = 'prescriptions';
        $d['page_name'] = 'updating_prescription';
        
        $this->load->view('Templates/Layouts/Doctor/header', $d);
        $this->load->view('Doctor/Prescription/Update', $d);
        $this->load->view('Templates/Layouts/Doctor/footer', $d);
    }

    public function sendAction()
    {
        if ($id_prescription = (int)$this->input->get_post('id')) {
            $prescObj = $this->ConsultationPrescriptionORM->getById($id_prescription);
            if ($prescObj->id_prescription) {
                if ($id_patient = $this->input->get_post('patient')) {
                    $patientObj = $this->UserEntityORM->getById($id_patient);
                   
                    if ($patientObj->id_user) {
                        $userObj = $this->UserEntityORM->getById($patientObj->id_user);
                            // Send the confirmation mail
                            $params = array(
                                'receiver' => $userObj->username,
                                'fromName' => $this->config->item('mail_from_name'),
                                'from'     => $this->config->item('mail_from'),
                                'subject'  => $this->l('Confirm your prescription'),
                                'to'       => $userObj->email,

                                // Params for the view

                                'connexion_link' => base_url('User/AccountService/signin/'),
                            );

                        if ($this->renderMail($params, 'SendPrescription')) {
                            $this->session->set_flashdata('successMessage', $this->l('Prescription successfully send to patient.'));
                        } else {
                            $this->session->set_flashdata('errorMessage', $this->l('The mail of information was not sent. Please contact our technical team.'));
                        }
                    
                    } else {
                    $this->session->set_flashdata('errorMessage', $this->l('An error occured. Bad HTTP request.'));
                }
            } else {
                $this->session->set_flashdata('errorMessage', $this->l('The target account was not found.'));
            }
            }
        } else {
            $this->session->set_flashdata('errorMessage', $this->l('An error occured. Bad HTTP request.'));
        }
        
        redirect('Doctor/Prescription/listing');
        die();
    }

    public function stopAction()
    {
        if ($id_prescription = (int)$this->input->get_post('id')) {

            $prescObj = $this->ConsultationPrescriptionORM->getById($id_prescription);
            
            if ($prescObj->id_prescription) {
                $ok = false;
                if ($this->input->get_post('act') == 'on') {
                    $prescObj->status = 0;
                    $ok = true;
                } elseif ($this->input->get_post('act') == 'off') {
                    $prescObj->status = 1;
                    $ok = true;
                }
                if ($ok) {
                    if ($this->ConsultationPrescriptionORM->save((array)$prescObj)) {
                        $consObj = $this->ConsultationORM->getById($prescObj->id_consultation);
                        $userObj = $this->UserEntityORM->getById($consObj->id_patient);
                        // Send the confirmation mail
                        $params = array(
                            'receiver' => $userObj->username,
                            'fromName' => $this->config->item('mail_from_name'),
                            'from'     => $this->config->item('mail_from'),
                            'subject'  => $this->l('Confirm your account'),
                            'to'       => $userObj->email,
                            
                            // Params for the view
                            
                            'connexion_link' => base_url('User/AccountService/signin/'),
                        );

                        if ($this->renderMail($params, 'SendPrescriptionStatus')) {
                            $this->session->set_flashdata('successMessage', $this->l('Prescription successfully updated.'));
                        } else {
                            $this->session->set_flashdata('errorMessage', $this->l('Prescription successfully updated. But the mail of information was not sent. Please contact our technical team.'));
                        }
                    } else {
                        $this->session->set_flashdata('errorMessage', $this->l('An error occured while saving update. Please try agin later.'));
                    }
                    } else {
                    $this->session->set_flashdata('errorMessage', $this->l('An error occured. Bad HTTP request.'));
                }
            } else {
                $this->session->set_flashdata('errorMessage', $this->l('The target account was not found.'));
            }
                
        } else {
            $this->session->set_flashdata('errorMessage', $this->l('An error occured. Bad HTTP request.'));
        }
         redirect('Doctor/Prescription/listing');
            die();    
        // $this->load->model('ORM/Consultation/ConsultationPrescriptionORM');
        /*$record = array(
            'id_prescription'=> $this->input->get_post('id'),
            'status'         => '0',
            'date_upd'       => @date('Y-m-d H:i:s'),
            );
        // Set the prescription status to off
        if ($this->ConsultationPrescriptionORM->save($record)) {
            // Redirect to the prescriptions list
            redirect('Doctor/Prescription/listing');
            die();
        } else {
            $this->session->set_flashdata('errorMessage', $this->l('An error occured while stopping your prescription. Please try again.'));
            redirect('Doctor/Prescription/listing');
            die();
        }*/
    }
    
    /* ==================================================
     *
     * PROTECTED FUNCTIONS
     * 
     * ================================================== */
    protected function getAllPrescriptions($id_doctor)
    {
                
        $prescription_table         = $this->ConsultationPrescriptionORM->getTableName();
        $prescription_table_primary = $this->ConsultationPrescriptionORM->getPrimaryKey();
        $cons_table                 = $this->ConsultationORM->getTableName();        
        $cons_table_primary         = $this->ConsultationORM->getPrimaryKey();
        $users_table                = $this->UserEntityORM->getTableName();        
        $users_table_primary        = $this->UserEntityORM->getPrimaryKey();
        $patients_table             = $this->UserPatientORM->getTableName();        
        $patients_table_primary     = $this->UserPatientORM->getPrimaryKey();
        
        //TODO : Enumarate fields to select because of date add 
        $this->db->select('precr.*, cons.*, users.*');
        $this->db->from($prescription_table.' as precr');
        $this->db->join($cons_table.' as cons', 'cons.'.$cons_table_primary.'='.'precr.'.$cons_table_primary, 'left');
        $this->db->join($users_table.' as users', 'cons.'.$patients_table_primary.'='.'users.'.$users_table_primary, 'left');
        $this->db->where('cons.id_doctor = '. (int)$id_doctor);
        
        $query = $this->db->get();

        return $query->result();
    }

    protected function getAllConsultations($id_doctor)
    {
        
        $prescription_type_table = $this->ConsultationTypeORM->getTableName();
        $prescription_type_table_primary = $this->ConsultationTypeORM->getPrimaryKey();
        
        //TODO : Join with the consultation type lang table 
        $cons_table             = $this->ConsultationORM->getTableName();        
        $cons_table_primary     = $this->ConsultationORM->getPrimaryKey();
        $users_table            = $this->UserEntityORM->getTableName();        
        $users_table_primary    = $this->UserEntityORM->getPrimaryKey();
        $patients_table         = $this->UserPatientORM->getTableName();        
        $patients_table_primary = $this->UserPatientORM->getPrimaryKey();
        
        $this->db->select('cons.*, users.*, cons_type.*');
        $this->db->from($cons_table.' as cons');
        $this->db->join($users_table.' as users', 'cons.'.$patients_table_primary.'='.'users.'.$users_table_primary, 'left');
        $this->db->join($prescription_type_table.' as cons_type', 'cons.'.$prescription_type_table_primary.'='.'cons_type.'.$prescription_type_table_primary, 'left');
        $this->db->where('cons.id_doctor = '. (int)$this->session->userdata('id_user'));
        $query = $this->db->get();

        return $query->result();
    }

    protected function getPrescriptionById($id_prescription)
    {
        
        $prescription_table         = $this->ConsultationPrescriptionORM->getTableName();
        $prescription_table_primary = $this->ConsultationPrescriptionORM->getPrimaryKey();
        $cons_table                 = $this->ConsultationORM->getTableName();        
        $cons_table_primary         = $this->ConsultationORM->getPrimaryKey();
        $users_table                = $this->UserEntityORM->getTableName();        
        $users_table_primary        = $this->UserEntityORM->getPrimaryKey();
        $patients_table             = $this->UserPatientORM->getTableName();        
        $patients_table_primary     = $this->UserPatientORM->getPrimaryKey();
        
        //TODO : Enumerate fields to select because of date add 
        $this->db->select('precr.*, cons.*, users.*');
        $this->db->from($prescription_table.' as precr');
        $this->db->join($cons_table.' as cons', 'cons.'.$cons_table_primary.'='.'precr.'.$cons_table_primary, 'left');
        $this->db->join($users_table.' as users', 'cons.'.$patients_table_primary.'='.'users.'.$users_table_primary, 'left');
        $this->db->where('precr.id_prescription = '.$id_prescription);
        $query = $this->db->get();

        return $query->row_array();
    }
}

